﻿#region MIT License
/*

Copyright (C) 2011 by Timothy A. Barela

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/
#endregion

using System;
using System.Collections.Generic;
using System.Diagnostics;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;

namespace Sharpener
{
	/*
	 "In principle, inlining is dead simple:
	 just replace the call of a function by an instance of its body.
	 But any compiler-writer will tell you that inlining is a black art,
	 full of delicate compromises that work together to give good performance
	 without unnecessary code bloat." 
	 - Secrets of the Glasgow Haskell Compiler inliner ( http://research.microsoft.com/en-us/um/people/simonpj/Papers/inlining/ ) 
	 */

	public class MethodInliningPass : Pass
	{
		public int CallSitesInlined { get; private set; }
		Dictionary<string, InlineMethod> inlineMethods;
						
		public override string StartingMessage
		{
			get { return "Inlining methods marked with the ForceInlineAttribute."; }
		}

		public override string ClosingMessage
		{
			get { return string.Format("{0} call sites's were expanded.", CallSitesInlined); }
		}

		public override bool Run( AssemblyDefinition assembly )
		{
			CallSitesInlined = 0;

			inlineMethods = InlineMethod.FindAll(assembly);

			processAssembly(assembly);

			removeInlineMethods(inlineMethods);
			
			return CallSitesInlined > 0;
		}
		
		private void processAssembly( AssemblyDefinition assembly )
		{
			foreach(var module in assembly.Modules)
				processModule(module);
		}

		private void processModule( ModuleDefinition module )
		{
			foreach(var type in module.Types)
				processType(type);
		}

		private void processType( TypeDefinition type )
		{
			foreach(var method in type.Methods)
			{
				if(method.HasBody)
				{
					var inlines = CallSitesInlined;
					var og = Utility.StringifyMethod(method);
				
					method.Body.SimplifyMacros();
					processMethod(method);
					InstructionHelper.FoldBranches(method.Body.Instructions);
					InstructionHelper.FoldNops(method.Body.Instructions);
					method.Body.OptimizeMacros();
				
					if(CallSitesInlined > inlines)
					{
						Debug.WriteLine("Original:");
						Debug.WriteLine(og);

						Debug.WriteLine("\nExpanded:");
						Debug.WriteLine(Utility.StringifyMethod(method));
					}
				}
			}
		}

		private void processMethod( MethodDefinition method )
		{
			var il = method.Body.GetILProcessor();
			var instructions=method.Body.Instructions;
						
			for(int index = 0; index < instructions.Count; index++)
			{
				var instr = instructions[index];

				if(instr.OpCode.FlowControl==FlowControl.Call)
				{
					var calleeRef = instr.Operand as MethodReference;
					InlineMethod patch;

					if(inlineMethods.TryGetValue(calleeRef.FullName, out patch))
					{
						Debug.Print("Callsite at {0:X4} ({1}) should be inlined.", instr.Offset, calleeRef.FullName);
												
						//expand( method, index, patch );
						patch.Inject(method, index);
						
						CallSitesInlined++;

						//we recurse... stackoverflow's > spinning endlessly
						processMethod(method);
						return;
					}
				}
			}
		}
				
		private void removeInlineMethods(Dictionary<string,InlineMethod> forceInlineMethods)
		{
			foreach(var method in forceInlineMethods.Values)
			{
				method.CleanUp();
			}
		}
	}
}